<template>
  <div class="flow-management">
    <div class="flow-header">
      <div class="breadcrumb">
        <el-breadcrumb>
          <el-breadcrumb-item>工作区管理</el-breadcrumb-item>
          <el-breadcrumb-item>{{ currentFile }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="actions">
        <el-button type="primary" @click="showAddFlowDialog">
          <el-icon><Plus /></el-icon>添加Flow
        </el-button>
        <el-button type="success" @click="showSmartGenerateFlowDialog">
          <el-icon><MagicStick /></el-icon>智能生成Flow
        </el-button>
      </div>
    </div>

    <div class="flow-container">
      <!-- 左侧：Flow列表 -->
      <div class="flow-list">
        <div class="section-title">Flow列表</div>
        <div class="flow-items">
          <div
            v-for="flow in flowStore.state.flows"
            :key="flow.id"
            class="flow-item"
            :class="{ active: selectedFlowId === flow.id }"
            @click="selectFlow(flow)"
          >
            <div class="flow-item-content">
              <div class="flow-id">{{ flow.id }}</div>
              <div class="flow-desc">{{ flow.description }}</div>
            </div>
            <el-button
              type="danger"
              size="small"
              @click.stop="confirmDelete(flow)"
              class="delete-btn"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>

      <!-- 右侧：Flow内容 -->
      <div class="flow-content">
        <div class="section-header">
          <div class="section-title">Flow编排图</div>
          <div class="section-actions" v-if="flowStore.state.selectedFlow">
            <el-button
              type="primary"
              :disabled="!isContentChanged"
              @click="saveFlowContent"
            >
              保存
            </el-button>
          </div>
        </div>
        <div class="flow-diagram">
          <div v-if="flowStore.state.flowContent" class="diagram-container">
            <el-input
              v-model="editableContent"
              type="textarea"
              :rows="20"
              class="flow-editor"
              @input="handleContentChange"
            />
          </div>
          <el-empty
            v-else
            description="选择一个Flow查看流程图"
          />
        </div>
      </div>
    </div>

    <!-- 添加Flow对话框 -->
    <el-dialog
      v-model="addFlowDialogVisible"
      title="添加新Flow"
      width="50%"
    >
      <el-form
        ref="addFlowForm"
        :model="newFlow"
        :rules="flowRules"
        label-width="80px"
      >
        <el-form-item label="ID" prop="id">
          <el-input v-model="newFlow.id" placeholder="请输入Flow ID" />
        </el-form-item>
        <el-form-item label="文件" prop="file">
          <el-input v-model="newFlow.file" placeholder="请输入Flow文件名" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="newFlow.description"
            type="textarea"
            :rows="3"
            placeholder="请输入Flow描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addFlowDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddFlow">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 智能生成Flow对话框 -->
    <el-dialog
      v-model="smartGenerateFlowDialogVisible"
      title="智能生成Flow"
      width="50%"
    >
      <el-form
        ref="smartGenerateFlowForm"
        :model="{ promptText }"
        label-width="80px"
      >
        <el-form-item label="描述" prop="promptText">
          <el-input
            v-model="promptText"
            type="textarea"
            :rows="5"
            placeholder="请输入您想生成的Flow的描述,注意这是一个流程图的描述，最好使用mermaid的格式"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="smartGenerateFlowDialogVisible = false" :disabled="isGeneratingFlow">取消</el-button>
          <el-button type="primary" @click="submitSmartGenerateFlow" :loading="isGeneratingFlow" :disabled="isGeneratingFlow">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useFlowStore } from '@/stores/flow';
import type { Flow } from '@/types/flow';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, MagicStick } from '@element-plus/icons-vue';

const flowStore = useFlowStore();
const addFlowDialogVisible = ref(false);
const smartGenerateFlowDialogVisible = ref(false); // Add this line
const addFlowForm = ref();
const isGeneratingFlow = ref(false); // Add this line

const newFlow = ref({
  id: '',
  file: '',
  description: '',
});

const promptText = ref(''); // Add this line

const flowRules = {
  id: [
    { required: true, message: '请输入Flow ID', trigger: 'blur' },
    { min: 3, message: 'ID长度至少为3个字符', trigger: 'blur' }
  ],
  file: [
    { required: true, message: '请输入Flow文件名', trigger: 'blur' },
    { pattern: /\.yaml$/, message: '文件名必须以.yaml结尾', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入Flow描述', trigger: 'blur' },
    { min: 5, message: '描述长度至少为5个字符', trigger: 'blur' }
  ]
};

const selectedFlowId = computed(() => flowStore.state.selectedFlow?.id || '');
const currentFile = computed(() => flowStore.state.selectedFlow?.file || 'dump_info.tar.gz');
const editableContent = ref('');
const isContentChanged = ref(false);

const handleContentChange = () => {
  isContentChanged.value = editableContent.value !== flowStore.state.flowContent?.content;
};

const saveFlowContent = async () => {
  if (!flowStore.state.selectedFlow) return;
  
  try {
    await flowStore.updateFlowContent(flowStore.state.selectedFlow.id, editableContent.value);
    isContentChanged.value = false;
    ElMessage.success('Flow内容保存成功');
  } catch (error) {
    console.error('Failed to save flow content:', error);
    ElMessage.error('Flow内容保存失败');
  }
};

// 监听选中的Flow内容变化
watch(() => flowStore.state.flowContent, (newContent) => {
  if (newContent) {
    editableContent.value = newContent.content;
    isContentChanged.value = false;
  } else {
    editableContent.value = '';
    isContentChanged.value = false;
  }
}, { immediate: true });

onMounted(async () => {
  console.log('FlowManagement component mounted');
  try {
    await flowStore.fetchFlows();
    console.log('Flows fetched:', flowStore.state.flows);
  } catch (error) {
    console.error('Error fetching flows:', error);
  }
});

const showAddFlowDialog = () => {
  newFlow.value = {
    id: '',
    file: '',
    description: '',
  };
  addFlowDialogVisible.value = true;
};

const submitAddFlow = async () => {
  if (!addFlowForm.value) return;
  
  await addFlowForm.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await flowStore.addFlow(newFlow.value);
        addFlowDialogVisible.value = false;
        ElMessage.success('Flow添加成功');
      } catch (error) {
        console.error('Failed to add flow:', error);
        ElMessage.error('Flow添加失败');
      }
    }
  });
};

const selectFlow = (flow: Flow) => {
  console.log('Selecting flow:', flow);
  flowStore.selectFlow(flow);
};

const confirmDelete = (flow: Flow) => {
  ElMessageBox.confirm(
    `确定要删除Flow "${flow.id}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await flowStore.deleteFlow(flow.id);
      ElMessage.success('Flow删除成功');
    } catch (error) {
      console.error('Failed to delete flow:', error);
      ElMessage.error('Flow删除失败');
    }
  });
};

const showSmartGenerateFlowDialog = () => {
  promptText.value = ''; // Reset prompt text
  smartGenerateFlowDialogVisible.value = true;
};

const submitSmartGenerateFlow = async () => {
  if (!promptText.value) {
    ElMessage.error('请输入Flow生成描述');
    return;
  }
  isGeneratingFlow.value = true; // Set to true when starting
  try {
    await flowStore.smartGenerateFlow(promptText.value);
    smartGenerateFlowDialogVisible.value = false;
    ElMessage.success('智能生成Flow成功');
  } catch (error) {
    console.error('Failed to smart generate flow:', error);
    ElMessage.error('智能生成Flow失败');
  } finally {
    isGeneratingFlow.value = false; // Always reset
  }
};
</script>

<style scoped>
.flow-management {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.flow-header {
  padding: 16px 20px;
  background-color: white;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.flow-container {
  flex: 1;
  display: flex;
  padding: 20px;
  gap: 20px;
  min-height: 0;
  height: calc(100vh - 120px); /* 减去头部和其他边距的高度 */
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}



.flow-list {
  width: 400px;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.flow-items {
  flex: 1;
  overflow-y: auto;
}

.flow-item {
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 8px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: all 0.3s;
}

.flow-item:hover {
  background-color: #f5f7fa;
}

.flow-item.active {
  background-color: #ecf5ff;
  border-color: #409eff;
}

.flow-item-content {
  flex: 1;
  min-width: 0;
  margin-right: 12px;
}

.flow-id {
  font-weight: 500;
  margin-bottom: 4px;
  color: #333;
}

.flow-desc {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.delete-btn {
  opacity: 0;
  transition: opacity 0.3s;
}

.flow-item:hover .delete-btn {
  opacity: 1;
}

.flow-content {
  flex: 1;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  min-width: 0;
  height: 100%;
  overflow: hidden;
}

.flow-diagram {
  flex: 1;
  border: 1px solid #f56c6c;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: calc(100% - 50px); /* 减去section-header的高度 */
}

.diagram-container {
  height: 100%;
  padding: 0;
}

.flow-editor {
  height: 100%;
}

.flow-editor :deep(.el-textarea) {
  height: 100%;
}

.flow-editor :deep(.el-textarea__inner) {
  height: 100% !important;
  resize: none;
  border: none;
  border-radius: 0;
  padding: 12px;
  font-family: monospace;
  line-height: 1.6;
  box-sizing: border-box;
}

pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

:deep(.el-breadcrumb) {
  font-size: 14px;
}

:deep(.el-empty) {
  padding: 40px 0;
}
</style>